package com.yxh.controller;

import com.alibaba.fastjson.JSONObject;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.yxh.common.annotation.Authorization;
import com.yxh.util.APIErrorCode;
import com.yxh.util.DateJsonValueProcessor;
import com.yxh.util.PageBean;
import com.yxh.util.Response;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.zip.ZipInputStream;

/**
 * Created by asus on 2018/6/2.
 */
@Scope("prototype")
@RestController
@RequestMapping(value = "/activity")
public class ActivityController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ActivityController.class);
    private Response response;

    @Autowired
    private RepositoryService repositoryService;
    /**
     * �ϴ����̲����ļ�
     *
     * @param deployFile
     * @param
     * @return
     * @throws Exception
     */

    @PostMapping
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response deploy(@RequestParam("deployFile") MultipartFile deployFile) throws Exception {
        try {
            repositoryService.createDeployment().
                    name(deployFile.getOriginalFilename()). //������������
                    addZipInputStream(new ZipInputStream(deployFile.getInputStream())) //���zipinputstream  newһ���ͺ�
                    .deploy();
            response = Response.returnResponse(APIErrorCode.SUCCESS);
        } catch (Exception e) {
             e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.FLOWDEPLOY_ERROR);
        }

        return response;
    }

    @GetMapping("/list")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response list(@RequestParam(required = false, defaultValue = "1", name = "page") String page,
                         @RequestParam(required = false, defaultValue = "10", name = "pageSize") String pageSize,
                         @RequestParam(required = false, name = "name") String s_name) throws Exception {

        try {
            if (s_name == null) {
                s_name = "";
            }

            PageBean pageBean = new PageBean();
            if (page != null) {
                pageBean.setPage(Integer.parseInt(page));
            }

            if (pageSize != null) {
                pageBean.setPageSize(Integer.parseInt(pageSize));
            }
            //  PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
            List<Deployment> deploymentList = repositoryService.createDeploymentQuery().   //创建流程部署查询
                    orderByDeploymentName().desc().         //根据部署时间降序排列
                    deploymentNameLike("%" + s_name + "%").     //根据流程部署名称模糊查询
                    listPage(pageBean.getStart(), pageBean.getPageSize());   //分页查询

            long total = repositoryService.createDeploymentQuery().deploymentNameLike("%" + s_name + "%").count();  //查询名字像这个总数
            JsonConfig jsonConfig = new JsonConfig();
            jsonConfig.setExcludes(new String[]{"resources"});
            jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss"));
            JSONObject result = new JSONObject();
            JSONArray jsonArray = JSONArray.fromObject(deploymentList, jsonConfig);
            result.put("rows", com.alibaba.fastjson.JSONObject.toJSONString(jsonArray));
            result.put("total", total);
            response= Response.returnResponse(APIErrorCode.SUCCESS);
            response.setData(result);

        } catch (Exception e) {
            e.printStackTrace();
            response = Response.returnResponse(APIErrorCode.SELECT_ERROR);
        }
        return response;
    }
    @DeleteMapping("/{ids}")
    @Authorization
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
    })
    public Response delete(@PathVariable(value = "ids") String ids) throws Exception {

        String[] strids = ids.split(",");

        for (String str : strids) {
            if (str != null) {
                repositoryService.deleteDeployment(str, true);   //是否级联删除
            }
        }
        response = Response.returnResponse(APIErrorCode.SUCCESS);

        return response;
    }
}
